#import "jokeTableViewController.h"
#import "SDRefresh.h"
#import "jokeModel.h"
#import "jokeTableViewCell.h"
#import "CommonAPI.h"
#import "collectTableViewController.h"

#import "AppDelegate.h"



#import "popupView.h"
#import "UIViewController+LewPopupViewController.h"
#import "LewPopupViewAnimationFade.h"
#import "LewPopupViewAnimationSlide.h"
#import "LewPopupViewAnimationSpring.h"
#import "LewPopupViewAnimationDrop.h"
#import "MzTableViewController.h"

#import "Reachability.h"


#import "ConectViewController.h"

#import "MyInterface.h"

#import "collectTableViewController.h"

#import "MJRefresh.h"



@interface jokeTableViewController ()

@property (nonatomic, weak) SDRefreshFooterView *refreshFooter;
@property (nonatomic, assign) NSInteger totalRowCount;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic,strong)UILabel *warmLabel;

//用于检测网络
@property (nonatomic ,strong)Reachability *r;

@end

@implementation jokeTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
  
    self = [super initWithStyle:style];
    if (self) {
    
        
    }
    return self;
}

- (void)viewDidLoad {
self.view.backgroundColor = [UIColor colorWithRed:245/255.0 green:254/255.0 blue:251/255.0 alpha:1.0];
    //隐藏cell之间的分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    

    self.navigationController.navigationBar.translucent = NO;
    
    self.tabBarController.tabBar.translucent = NO;
    
//    UIActivityIndicatorView *act = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhite)];
//    act.frame = CGRectMake(100, 100, 100, 100);
//    act.backgroundColor = [UIColor blackColor];
//    [self.view addSubview:act];
    

    
    self.r = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    
    if  ([self.r currentReachabilityStatus]== NotReachable){
        
        UIAlertView *warming = [[UIAlertView alloc]initWithTitle:@"警告" message:@"没有检测到网络,请联网后刷新再试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [warming show];
        
    }
    [self setupRefresh];
    
    
    
    //如果没有刷新到数据,请用户重试
    self.warmLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, self.view.frame.size.height/4, self.view.frame.size.width, 40)];
    [self.view addSubview:_warmLabel];

    
    
    
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    //    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // dateKey用于存储刷新时间，可以保证不同界面拥有不同的刷新时间
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing) dateKey:@"table"];
    
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"数据正在加载中,请稍后";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.tableView.footerRefreshingText = @"数据正在加载中,请稍后";
}
- (void)headerRereshing
{
    // 1.添加数据
    __weak typeof (self) weakSelf = self;
    [CommonAPI firstJokeListData:^(id data) {
        weakSelf.dataArray = data;
    }];
    
    
    // 2.模拟2秒后刷新表格UI（真实开发中，可以移除这段gcd代码）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
      
      
    });
}

- (void)footerRereshing
{
    // 1.添加数据
    jokeModel *m = self.dataArray.lastObject;
    __weak typeof (self) weakSelf = self;
    [CommonAPI downJokeListstring:m.cTime Data:^(id data) {
        NSArray *arr = [[NSArray alloc]initWithArray:data];
        [weakSelf.dataArray addObjectsFromArray:arr];
        
    }];
    
    
    // 2.模拟2秒后刷新表格UI（真实开发中，可以移除这段gcd代码）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView footerEndRefreshing];
    });
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    jokeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"jokeTableViewCell" forIndexPath:indexPath];
    
    //设置cell选中时候的颜色为透明色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    

    
    jokeModel *n = self.dataArray[indexPath.row];
    
    cell.jokeLabel.text = n.title;
    
    
    
    
    
    return cell;
}

//返回cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    
    jokeModel *m = [[jokeModel alloc]init];
    
    m = self.dataArray[indexPath.row];
    
    
    
    
    return [jokeTableViewCell cellFloatWithModel:m];
    
   
    
}

- (IBAction)sss:(id)sender {
    popupView *view = [popupView defaultPopupView];
    view.parentVC = self;
    [view.button addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
    
    [view.clearButton addTarget:self action:@selector(clearAction) forControlEvents:UIControlEventTouchUpInside];
    
    [view.fiveButton addTarget:self action:@selector(fiveAction) forControlEvents:UIControlEventTouchUpInside];
    
    [view.mzButton addTarget:self action:@selector(mzAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self lew_presentPopupView:view animation:[LewPopupViewAnimationDrop new] dismissed:^{
       NSLog(@"动画结束");
    }];
}

- (void)push
{
//    collectTableViewController *collView = [[collectTableViewController alloc]init];
//    
//    [self.navigationController pushViewController:collView animated:YES];
    
    NSLog(@"我的收藏");
    
}

- (void)clearAction
{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [appDelegate.myCache clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
    
    NSLog(@"清空缓存");

    UIAlertView *aleraView = [[UIAlertView alloc]initWithTitle:@"恭喜" message:@"缓存已经清空" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [aleraView show];
}

- (void)fiveAction
{
    NSLog(@"联系我们");
    ConectViewController *coView = [[ConectViewController alloc]init];
    [self.navigationController pushViewController:coView animated:YES];
    

    
    
}

- (void)mzAction
{
    MzTableViewController *mzView = [[MzTableViewController alloc]init];
    
    [self.navigationController pushViewController:mzView animated:YES];
    
    NSLog(@"免责声明");
    
}

- (IBAction)collect:(UIButton *)sender {
    
    //响应者链建立连接(在Cell上点击没有反应)
    jokeTableViewCell *cell = (jokeTableViewCell*)sender.superview.superview;
    
    jokeModel *joke = [[jokeModel alloc] init];
    joke.title = cell.jokeLabel.text;
    
    NSArray *jokeArray = [MyInterface selectWithAllJoke];
    for (jokeModel *j in jokeArray) {
        if ([j.title isEqualToString:cell.jokeLabel.text]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已经收藏过了" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
    }
    
    [MyInterface insertWithJoke:joke];
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    

}





@end
